//
//  OrderDetailsViewController.m
//  SeaMelonSeeds_Counselor
//
//  Created by 尤振宇 on 2017/7/28.
//  Copyright © 2017年 杨笑. All rights reserved.
//

#import "OrderDetailsViewController.h"
#import "OrderDetailsTableViewCell.h"
#import "Order.h"
#import "DiagnosisRecordViewController.h"
#import "PersonalDetailsViewController.h"
#import "OrderApi.h"
#import "ClassificationViewController.h"
#import "ClassificationCell.h"
#import "GaugeApi.h"
#import "CheckScaleViewController.h"
#import "CompleteOrderClassificationVC.h"

@interface OrderDetailsViewController () <ClassificationDelegate>
@property(nonatomic,strong)NSMutableArray *selecteds;
@property(nonatomic,weak)OrderService *submitService;
@end

@implementation OrderDetailsViewController

+(OrderDetailsViewController *)OrderDetailsViewController:(Order *)order
{
    OrderDetailsViewController *vc = [[OrderDetailsViewController alloc]init];
    vc.order = order;
    return vc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"订单详情";
    self.tableView.bounces = YES;
    [self addMj_header];
    [self loadData];
    [self.tableView registerCellWithNib:@"OrderDetailsTableViewCell"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:kAppDidBecomeActive object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)scaleSubmit
{
    WeakSelf(self)
    OrderApi *api = [[OrderApi alloc]initRequestSendGaugeWithServiceID:self.submitService.id gauge_ids:self.selecteds];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        if (kCode(request.responseJSONObject)) {
            self.submitService.allow_send_gauge = NO;
            [MBProgressHUD showSuccess:@"已提交"];
            [self.navigationController popViewControllerAnimated:YES];
            [Tool SendMessage_testTable:_order.id hx_username:_order.user_hx serviceID:self.submitService.id];
        }
        [weakself.tableView reloadData];
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
    }];
}

-(void)loadData
{
    WeakSelf(self)
    OrderApi *api = [[OrderApi alloc]initRequestDetailWithOrderID:self.order.id];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        if (kCode(request.responseJSONObject)) {
            [weakself.dataArray removeAllObjects];
            NSArray *arr = [[request.responseJSONObject objectForKey:@"data"] objectForKey:@"list"];
            for (NSDictionary *dic in arr) {
                OrderService *service = [OrderService new];
                [service setValuesForKeysWithDictionary:dic];
                [weakself.dataArray addObject:service];
            }
        }
        [weakself.tableView reloadData];
        [weakself endRefreshing];
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [weakself endRefreshing];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderService *service = self.dataArray[indexPath.row];

    OrderDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailsTableViewCell" forIndexPath:indexPath];
    WeakSelf(self)
    [cell setOrder:service];
    cell.tableAction = ^(id obj) {
        
        if (!service.allow_send_gauge) {
            CheckScaleViewController *vc = [[CheckScaleViewController alloc]init];
            vc.orderService = service;
            [weakself pushViewController:vc animated:YES];
            
        }else{
            //发送量表
            [weakself pushClassification];
            weakself.submitService = service;
        }
    };
    
    cell.detailsAction = ^(id obj) {
        if ([weakself.updataTableViewController isMemberOfClass:[CompleteOrderClassificationVC class]]) {
            [weakself pushViewController:[PersonalDetailsViewController PersonalDetailsViewController:nil UserID:self.order.user_id] animated:YES];
        }else{
            [weakself pushViewController:[PersonalDetailsViewController PersonalDetailsViewController:self.order UserID:self.order.user_id] animated:YES];
        }
        
    };
    
    cell.otherAction = ^(id obj) {
        [weakself otherAction:service];
    };
    
    cell.depoyabel.spreadText = ^(id obj) {
        [CALayer cancelAnimation:^{
            [weakself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];

        }];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Order *order = self.dataArray[indexPath.row];
    return 125 + [order cellHeight];
}

-(void)otherAction:(OrderService *)service
{
    WeakSelf(self)
    if (service.status == 0) {
        
        [self alertController:@"确认服务开始" handler:^(UIAlertAction *action) {
            OrderApi *api = [[OrderApi alloc]initRequestServiceBeginWithServiceID:service.id];
            [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                if (kCode(request.responseJSONObject)) {
                    [Tool SendMessage_ServiceBegan:weakself.order.id hx_username:weakself.order.user_hx serviceID:service.id];
                    weakself.updataViewController.isViewWillAppearUpdata = YES;
                    [weakself loadData];
                    if (service.surplus_minites > 0) {
                        [self alertController:@"语音服务开始，注意接听来电"];
                    }
                }
            } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                
            }];
        }];
    }else if (service.status == 1){
        
        if (service.surplus_minites > 0) {
            
            UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"继续通话/结束" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
            
            UIAlertAction *action1=[UIAlertAction actionWithTitle:@"继续通话" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                [alert dismissViewControllerAnimated:YES completion:nil];

                OrderApi *api = [[OrderApi alloc]initRequestCall:service.id];
                [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                    if (kCode(request.responseJSONObject)) {
                        [self alertController:@"语音咨询开始，注意接听来电"];
                    }
                } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                    
                }];
                
                
                
            }];
            
            UIAlertAction *action2=[UIAlertAction actionWithTitle:@"服务结束" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                [alert dismissViewControllerAnimated:YES completion:nil];

                OrderApi *api = [[OrderApi alloc]initRequestServiceEndWithServiceID:service.id];
                [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                    if (kCode(request.responseJSONObject)) {
                        [Tool SendMessage_ServiceEnd:weakself.order.id hx_username:weakself.order.user_hx serviceID:service.id];
                        weakself.updataViewController.isViewWillAppearUpdata = YES;
                        [weakself loadData];
                    }
                } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                    
                }];
            }];
            
            UIAlertAction *action3=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [alert dismissViewControllerAnimated:YES completion:nil];

            }];
            
            [alert addAction:action1];
            [alert addAction:action2];
            [alert addAction:action3];
            [self presentViewController:alert animated:YES completion:nil];
            
        }else{
            [self alertController:@"确认服务结束" handler:^(UIAlertAction *action) {
                OrderApi *api = [[OrderApi alloc]initRequestServiceEndWithServiceID:service.id];
                [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                    if (kCode(request.responseJSONObject)) {
                        [Tool SendMessage_ServiceEnd:weakself.order.id hx_username:weakself.order.user_hx serviceID:service.id];
                        weakself.updataViewController.isViewWillAppearUpdata = YES;
                        [weakself loadData];
                    }
                } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                    
                }];
            }];
        }
    }else if (service.status == 2){
        if (service.allow_create) {
            DiagnosisRecordViewController *vc = [[DiagnosisRecordViewController alloc]init];
            vc.orderService = service;
            vc.order = weakself.order;
            [self pushViewController:vc animated:YES];
        }else{
            //查看诊断记录
            DiagnosisRecordViewController *vc = [[DiagnosisRecordViewController alloc]init];
            vc.orderService = service;
            vc.order = weakself.order;
            vc.isFinish = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

-(void)alertController:(NSString *)title handler:(void (^ __nullable)(UIAlertAction *action))handler
{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:title message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction *action1=[UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [alert dismissViewControllerAnimated:YES completion:nil];
        handler(action);
    }];
    
    UIAlertAction *action2=[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        [alert dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    
    [self presentViewController:alert animated:YES completion:nil];
}
-(void)alertController:(NSString *)title
{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:title message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}


-(void)pushClassification
{
    [MBProgressHUD showMessage:@"正在加载..."];
    GaugeApi *api = [[GaugeApi alloc]init];
    api.needHUD = NO;
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUD];
        if (kCode(request.responseJSONObject)) {
            NSMutableArray *data = [NSMutableArray array];
            NSArray *arr = [request.responseJSONObject objectForKey:@"data"];
            for (NSDictionary *dic in arr) {
                Scale *scale = [[Scale alloc]init];
                [scale setValuesForKeysWithDictionary:dic];
                [data addObject:scale];
            }
            
            ClassificationViewController *vc = [[ClassificationViewController alloc]initWithDelegate:self registeredCell:^(UITableView *tableView) {
                
                [tableView registerNib:[UINib nibWithNibName:@"ClassificationCell" bundle:nil] forCellReuseIdentifier:@"ClassificationCell"];
            }];
            
            vc.title = @"全部量表";
            vc.categoryTableCellWidth = 90;
            vc.categoryTableCellHieght = 50;
            
            vc.navigationItem.rightBarButtonItem = [Tool BarButtonItemWithTitle:@"提交" target:self action:@selector(scaleSubmit)];
            
            [vc addDataArr:data];
            
            vc.categoryDefaultBackgroundColor = kF2F2F2;
            vc.categorySelectBackgroundColor = [UIColor whiteColor];
            [self pushViewController:vc animated:YES];
        }else{
            [MBProgressHUD showError:@"测试量表获取失败"];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUD];
    }];
}

-(UITableViewCell *)classificationVC:(ClassificationViewController *)classificationVC contentTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath andModel:(id)model
{
    ClassificationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ClassificationCell" forIndexPath:indexPath];

    Scale *subClass = model;
    WeakSelf(self)
    cell.selectBtn.selected = subClass.selected;
    cell.title.text = subClass.title;
    cell.price.text = [NSString stringWithFormat:@"%@%0.2f",RENMINGBI,subClass.price];
    [cell.image sd_setImageWithURL:[NSURL URLWithString:subClass.image]];

    cell.selectAction = ^(UIButton *obj) {
        subClass.selected = obj.selected;
        if (obj.selected) {
            if (weakself.selecteds.count == 3) {
                subClass.selected = NO;
                obj.selected = subClass.selected;
                [MBProgressHUD showError:@"最多选择3个量表"];
                return ;
            }
            
            [classificationVC selcetObject:model];
            [weakself.selecteds addObject:@(subClass.id)];
        }else {
            [classificationVC cancelSelcetObject:model];
            [weakself.selecteds removeObject:@(subClass.id)];
        }
    };

    return cell;
}
-(UIView *)classificationVC:(ClassificationViewController *)classificationVC contentTableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section andModel:(id<CategoryModel>)model
{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 90, 30)];
    label.backgroundColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:14];
    label.text = model.categoryTitle;
    return label;
}
-(CGFloat )classificationVC:(ClassificationViewController *)classificationVC contentTableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section andModel:(id<CategoryModel>)model
{
    return 30;
}

-(CGFloat)classificationVC:(ClassificationViewController *)classificationVC contentTableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath andModel:(id)model
{
    return 75;
}

-(NSMutableArray *)selecteds
{
    if (!_selecteds) {
        _selecteds = [NSMutableArray array];
    }
    return _selecteds;
}


-(void)dealloc
{
    NSLog(@"%@ 释放了!!!",[self class]);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
